<template>
	<div class="box confirm-order-box" >
		<div v-if="!confirmOrderFood">
			<confirm-order-header></confirm-order-header>
		</div>
        <my-header  v-if="confirmOrderFood" :title="'确认订单'"  :hasBacks="true" :goBack="goBack" :canteen ="true"></my-header>
        <!-- <div class="sbbjclass"> -->
		<!-- <div class="content" id="nodeBug"  :style="`height: ${screenHeight}px`" > -->
		<div class="content bs-wrapper" id="nodeBug" >
            <!-- <vertical-scroll ref='verticalScroll' :clicks="false"> -->
                <!-- 绿色围脖 -->
                <!-- <div class="confrimOrderTopBar" v-if="!confirmOrderFood">

                </div> -->
                <!-- <div class="contentnew" style="position:absolute;top:0;left:0;width:100%;z-index:1;" > -->
                <div class="contentnew" >
                        <div class="confrimOrderTopBar" v-if="!confirmOrderFood">

                        </div>
                        <!-- 地址和配送时间组件 -->
                        <div class="confrimOrderTimeAddressBox" v-if="!confirmOrderFood">
                            <div class="confrimOrderAddressBox">
                                <confirm-order-address></confirm-order-address> 
                            </div>
                            <div class="confrimOrderTimeBox">
                                <confirm-getTime ref="nomalTimeshow" :data1 = "normalTimeList" :data2 = "bigTimeList" :checkedCartListNormal="checkedCartListNormal" :checkedCartListBig="checkedCartListBig" :hasBigFlag="checkedCartListBig.length > 0?true:false" :marks="marks"></confirm-getTime>
                            </div>
                        </div>
                        <!-- 配送方式组件 -->
                        <div style="width:100%;margin-top:0.75rem;" v-if="!confirmOrderFood">
                            <confirm-send-methods></confirm-send-methods>									<!--idName="name1" :flag= true-->
                        </div>
                        <!-- 堂食订单组件 -->
                        <Confirm-Hint v-if="confirmOrderFood"></Confirm-Hint>
                        <ConfirmOrderFoodInfo :userPhone = "userInfo" v-if="confirmOrderFood"></ConfirmOrderFoodInfo>

                        <!-- 商品列表组件 -->
                        <div style="width:100%;">
                            <confirm-order-list :confirmOrderFood="confirmOrderFood" :goodsMoney="goodsMoney"  :checkedCartList="checkedCartList" :checkedCartListNormal="checkedCartListNormal" :checkedCartListBig="checkedCartListBig" :flag= true :delFlag="delFlag"></confirm-order-list>
                            <!-- -->
                            <confim-order-send-gift  v-if="getGiftSendArr.length > 0"></confim-order-send-gift>
                        </div>
                        <!-- 发票组件 -->
                        <div style="width:100%;">
                            
                        </div>
                        <!-- 金额信息组件 -->
                        <div style="width:100%;">
                            <confirm-order-detail :confirmOrderFood="confirmOrderFood" @changeGoodsMoney="getGoodsMoney"  @sendGoodsList="cartList" :sendOrder="checkStoreRange" @sendWithoutMoney="getMoneyWithoutCode" @changeTotalMoney="getTotalMoney" :checkedCartList="checkedCartList" :normalList="checkedCartListNormal" :bigList="checkedCartListBig" :sendMoney="sendMoney"></confirm-order-detail>
                        </div>
                        <!-- <div style="width:100%;height:300px;background:green;">

                        </div> -->
                
                </div>
            <!-- </vertical-scroll> -->
            
			<!--<div id="bottomNode">-->
			
			<!-- <confirm-order-detail></confirm-order-detail> -->
			<!--</div>-->
		</div>
        <!-- </div> -->
        <!-- 底部悬浮提示 -->
        <!-- <div class="zx_message">
            <div style="color:rgb(239, 84, 35);">所购商品缺货</div>
            <div>，其他商品继续配送（ 缺货商品退款 ）</div>
        </div> -->
         <!-- 底部悬浮提示 -->
        <shops-Lack ></shops-Lack>
		<div class="zxSettle_acount">
			<div class="zxBottomBtn" @click.stop="checkStoreRange">
                <div class="zxSendOrderPrice" >
                    <span > 应付： </span>
                    <span style="color:#ef5423;font-weight:bold;font-size:1rem;">¥ {{totalMoney.toFixed(2)}}</span>
                </div>
                <div class="zxSendOrder">提交订单</div>
            </div>
		</div>
        <confrimOrderPopout ref="popoutCover" :text="texts" ></confrimOrderPopout>
	</div>
</template>

<script>

// import ConfirmOrderDetail from "./ConfirmOrderDetail";
import ConfirmOrderHeader from "./ConfirmOrderHeader";
import {mapGetters,mapActions,mapMutations} from "vuex";
import axios from 'axios';
import {Toast} from '../../utils/toast';
import {showLoading, hideLoading} from "../../utils/loading";
import ConfirmGetTime from "../../real-components/ConfirmOrderNew/ConfirmOrderGetTime";
import ConfirmOrderList from "../../real-components/ConfirmOrderNew/ConfirmOrderGoodsList";
import ConfimOrderSendGift from "../../real-components/ConfirmOrderNew/ConfimOrderSendGift";
import ConfirmOrderDetail from "../../real-components/ConfirmOrderNew/ConfirmOrderDetail"; //生产
// import ConfirmOrderDetail from "../../real-components/ConfirmOrderNew/ConfirmOrderDetailTest"; //本地
import ConfirmSendMethods from "../../real-components/ConfirmOrderNew/ConfirmSendMethods";
import shopsLack from "../../real-components/ConfirmOrderNew/shopsLack"; //生产
import {normal} from "../../config/orderTypeCode";
import {tangshi} from "../../config/orderTypeCode";
import {MessageBox} from '../../ui-components';
import ConfirmOrderAddress from "./ConfirmOrderAddress";
import ConfirmHint from "../../real-components/ConfirmOrderFood/ConfirmOrderHint";
import ConfirmOrderFoodInfo from "../../real-components/ConfirmOrderFood/ConfirmOrderFoodInfo";
import MyHeader from "../header";
import Bscroll from 'better-scroll';
import changeOrderTm from "../../utils/ZX/changeOrderTm"
// import VerticalScroll from '../../real-components/VerticalScroll';
import confrimOrderPopout from '../../real-components/confrimOrderPopout';
export default {
    name: 'hello',
    data () {
        return {
            msg: '这是确认订单页面',
            page: "comfirmOrder",
            checkedCartList:[],   //购物车所有商品
            checkedCartListNormal:[],   //用于存放常规商品的数组
            checkedCartListBig:[],  //用于存放大件商品的数组
            maxTimeNormal:[],   //用于请求时间列表接口的参数
            maxTimeBig:[],    //用于请求时间列表接口的参数
            normalTimeList:[], //用于接收常规商品时间列表请求结果
            bigTimeList:[],   //用于接收大件商品时间列表请求结果
            shopCartIds:[],      //用于下单的参数
            address:null,
            sendMoney:[],
            supportInvoiceFlag:false,
            myMap:null, // 地图对象
            storeRange:null,  // 配送范围
            moneyWithoutC:0 , //钱包免密金额
            totalMoney:0,  // 应付金额
            keyall:null , // 钱包密码
            showMask:false, //是否需要用戶輸入密碼
            delFlag:0,   // 用于修改样式
            clickFlag:true,  // 防止两次快速点击 调用两次下单接口
            showTimeFlag:false,  // 控制选择常规时间的弹出框是否显示
            goodsMoney:0, // 商品总金额
            getDateFromCatch:false,// 是否从缓存获取数据
            // msg:"",
            confirmOrderFood:false,//是否从堂食购物车过来
            isOpenShops:null,//判断门店是否开启
            marks: false,//判断配送时间是否返回数据
            tempTm:true,//配送时间是否符合的标志
            texts:null,//弹出框的标题
        }
    },
    computed: {
        ...mapGetters('wxh',[
            'sessionId',
            'userInfo'
        ]),
        ...mapGetters('qxz',[
        	"getLocation"
        ]),
        ...mapGetters('zx',[
            'getAddressDetail','getMynode',"getTimeNormal","getTimeBig","getNormalM","getBigM",
            "getDeliveryType","getFpObj","getTicketList","getLadderIdList","getGiftVOList",
            "getStoreNow","getUseGiftCard","getAvailAmount","getGiftSendArr","getToken","getOrderFlag","getTimeSaveObj"
        ]),
        ...mapGetters('hzh',[
            'PutAShopLacks','PutAShopLacksFood'
        ]),
        getConfirmobile() {
            return this.$store.state.hzh.foodInfor1;
        },
        getConfirstyle() {
            return this.$store.state.hzh.foodInfor2;
        },
        domYuansu(){
            return document.querySelector(".mint-msgbox-message") || "";
        }
        // screenHeight() {
        //     return window.innerHeight - '180';
        // },
    },
    watch:{
        domYuansu(newVal,oldVal){
            console.log(newVal,"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++",oldVal);
        }
    },
    components: {
        "confirm-order-header":ConfirmOrderHeader,
        "confirm-order-detail": ConfirmOrderDetail,
        "confirm-getTime": ConfirmGetTime,
        "confirm-order-list": ConfirmOrderList,
        "confirm-send-methods":ConfirmSendMethods,
        "confirm-order-address":ConfirmOrderAddress,
        "confim-order-send-gift":ConfimOrderSendGift,
        "shops-Lack":shopsLack,
        "Confirm-Hint": ConfirmHint,
        "ConfirmOrderFoodInfo": ConfirmOrderFoodInfo,
        "my-header": MyHeader,
        // "vertical-scroll": VerticalScroll,
        "confrimOrderPopout": confrimOrderPopout,
    },
    methods: {
        ...mapMutations('zx',[
            "setTimeNormal","setTimeBig","setFpObj","setTicketList","setConfrimOrderRes",
            "setUseGiftCard","setMynode","setDateNormal","setDateBig","setTimeSaveObj",
            "setaddFlagMutation","setNowAddressMutation","setToken","setOrderFlag","setFpInfo",
            "setNormalM", "setBigM",
        ]),
        ...mapMutations('cjy',[
            "changeCheckedCartList"
        ]),
        //解决支付按钮不固定
        // appendToPay(){
        // 	setTimeout(()=>{
        // 		document.querySelector(".confirm-order-box").appendChild(document.querySelector(".zxSettle_acount"))
        // 	},300)
        // }
        // change(msg){
        //     console.log("change,msg",msg)
        //     this.msg = msg;
        // },
        getGoodsMoney(m){
            this.goodsMoney = m;
        },
        goBack() {
            window.history.back();
        },

        //获取最大时间
        getMaxTime(arr){
            // console.log(arr,"常规 大件”");
            if(arr.length > 0){
                var max1 = arr[0].distributionpreparationtime;
                var max2 = arr[0].distributionprocessingtime;
                var myArr = [];
                for(let i = 0; i < arr.length; i++){
                    if(max1 < arr[i].distributionpreparationtime){
                        max1 = arr[i].distributionpreparationtime;
                    }
                    if(max2 < arr[i].distributionprocessingtime){
                        max2 = arr[i].distributionprocessingtime;
                    }
                }
                myArr.push(max1);
                myArr.push(max2);

                return myArr;
            }
        },
        //获取初始数据
        cartList(e){
            //获取所有购物车商品
            // this.checkedCartList = this.$store.state.cjy.checkedCartList;
            this.checkedCartList = e;
            // console.log()
            // 选择优惠券会重新执行该方法，商品会不断push 每次先清除数据
            this.checkedCartListNormal = [];
            this.checkedCartListBig = [];
            //区分大件商品和常规商品  0 常规   1 大件
            for(var i = 0; i < this.checkedCartList.length; i++){
                var obj = {}
                obj['rid'] = this.checkedCartList[i].rid;
                this.shopCartIds.push(obj);
                console.log(this.checkedCartList[i],this.checkedCartList[i].rid,'商品唯一标志')
                if(this.checkedCartList[i].distributiontype === 0 || this.checkedCartList[i].distributiontype === null){
                    this.checkedCartListNormal.push(this.checkedCartList[i]);
                }else if(this.checkedCartList[i].distributiontype === 1){
                    this.checkedCartListBig.push(this.checkedCartList[i]);
                }
            }
            //获取到常规和大件的加工时间 准备时间
            this.maxTimeNormal = this.getMaxTime(this.checkedCartList);
            this.maxTimeBig = this.getMaxTime(this.checkedCartListBig);

            var obj = this.getTimeSaveObj;
            let flag = this.checkObj(obj);
            if(!flag){
                this.getTimeUserChoose();
                //此时没有调用配送时间接口所以要将下单按钮置为 true;
                 this.setOrderFlag(true);  // 获取配送时间信息  允许用户点击提交订单按钮
                //  console.log('影城因此过后就会开花')
                 this.getDateFromCatch = true;
            }else{
                //请求昌松的可选时间接口   获取时间列表
                if(this.checkedCartListNormal.length > 0 && !this.confirmOrderFood){
                    this.getTimeList(this.maxTimeNormal,0);
                }
                if(this.checkedCartListBig.length > 0 && !this.confirmOrderFood){
                    this.getTimeList(this.maxTimeBig,1);
                }
            }


        },
        //判断对象是否为空的方法
        checkObj(obj) {
            for(var key in obj) {
                return false;
            }
            return true;
        },
        //从vue中 获取用户已经选择了的配送时间数据
        getTimeUserChoose(){
            var obj = this.getTimeSaveObj;
            this.normalTimeList = obj.data1;
            //大件的配送时间
            this.bigTimeList = obj.data2;
            // console.log(this.normalTimeList,this.bigTimeList,'大件商品常规商品哈哈哈哈哈哈哈')
        },
        //获取用户收货地址
        getToPayAddress(){
            var myAddress = this.getLocation;
            // console.log(myAddress,'我的收货地址')
            let arr = this.userInfo.addressLists;
            var query = null;
            if(this.$route.query && this.$route.query.name){
                    query = JSON.parse(this.$route.query.name);
            }
            if(query && query.flag){
                this.address = query;
                return true;
            }else if(myAddress && myAddress.addressid == -1){
                var address = {
                    address:myAddress.address,
                    city:myAddress.city,
                    defaultaddress:"1",
                    label:"0",
                    phone:"",
                    positionlat:myAddress.positionlat,
                    positionlng:myAddress.positionlng,
                    province:myAddress.province,
                    receivername:"",
                    region:myAddress.region,
                    result:"",
                    sex:"0",
                    houseNumber:''
                }
                this.setaddFlagMutation(true);
                this.setNowAddressMutation(address);

                //存local 防止vuex失效  当失效时取用
                localStorage.setItem('userAddressNow',JSON.stringify(address));

                // this.$router.push({ path: 'addAddress',query:{id:1,obj:JSON.stringify(address)}});
                this.$router.push({ path: 'address',query:{id:1}});
                return false;

            }else if(myAddress && myAddress.addressid != -1){
                this.address = myAddress;
                return true;
            }else{
                return true;
            }
        },
        //获取时间列表方法
        getTimeList(data,type){
            console.log(data,type)
            let params = {
                readyTm:data[0],
                machineTm:data[1],
                storeCode:localStorage.getItem('storeCode')
            };
            let config = {
                url:window.api.trade_host+"/delivery_config/tm_interval/"+type,
                method: 'GET',
                params,
                headers: {'sessionId': this.sessionId},
            };
            this.marks = true;
            console.log(config.url)
            axios(config).then((res)=>{
                console.log(res.data.data,'shiajianliebaios',type);
                if(res.data.returnCode == 0){
                    hideLoading();
                    MessageBox.confirm('商品失效请重新下单').then((action)=>{
                        this.$router.push('cart');
                        
                    })
                    return
                }
                this.marks = false;
                if(type === 0){
                    if(res.data.data && res.data.data.length){
                        this.normalTimeList = res.data.data;
                        // console.log(res.data.data,'~~~~~~~~时间~~~~~')
                        //初始化store中的时间
                        hideLoading();
                        for(let i = 0; i < res.data.data[0].deliveryList.length;i++){
                            // if(res.data.data[0].deliveryList[i].valid == 1){
                            if(res.data.data[0].deliveryList[i].valid == 1){
                                this.setTimeNormal(res.data.data[0].deliveryList[i]);
                                this.setOrderFlag(true);  // 获取配送时间信息  允许用户点击提交订单按钮
                                return
                            }
                        }
                    }

                }else if(type === 1){
                    this.bigTimeList = res.data.data;
                    if(res.data.data[0]){
                        hideLoading();
                        for(let i = 0; i < res.data.data[0].deliveryList.length;i++){
                            // if(res.data.data[0].deliveryList[i].valid == 1){
                            if(res.data.data[0].deliveryList[i].valid == 1){
                                this.setTimeBig(res.data.data[0].deliveryList[i]);
                                this.setOrderFlag(true);  // 获取配送时间信息  允许用户点击提交订单按钮
                                
                                return
                            }
                        }
                    }
                }
                
            }).catch((err)=>{
                // 隐藏loading
                hideLoading();
                MessageBox.confirm('商品失效请重新下单').then((action)=>{
                    this.$router.push('cart');
                    
                })
                return
            })
        },
        //获取起送额
        getmoneySend(){
            let config = {
                url:window.api.trade_host+"/delivery_config/delivery/"+localStorage.getItem('storeCode'),
                method: 'GET',
                headers: {'sessionId': this.sessionId},
            };
            axios(config).then((res)=>{
                this.sendMoney = res.data.data[0];
            })
        },
        //判断是否展示发票入口
        supportInvoice(){
            this.supportInvoiceFlag = this.getConfigParams.supportInvoice;
        },
        innitFpData(){
            let url = window.api.service_host + '/mallconfig/selectInvoice';
            let config = {
                url: url,
                method: 'GET',
                headers: {
                    'sessionId': this.sessionId
                },
            };
            axios(config).then((res)=>{
                var str = ''; // 用于存放发票内容
                if(res.data.returnCode === 1){
                    var fpInfo = res.data.data[0];
                    this.supportInvoiceFlag = res.data.data[0].supportInvoice;
                    this.setFpInfo(fpInfo);
                }
            })
        },
        // 去发票页面
        toFp(){
            this.$router.push("orderfpInfo")
        },
        //获取优惠券参数
        getCouponParams(){
            var newArr = [];
            let arr = this.getTicketList || [];
            for(let i = 0 ; i < arr.length; i++){
                newArr.push(arr[i].qrCode);
            }
            return newArr;
        },
        // 获取订单返利参数
        getLadderParams(){
            return this.getLadderIdList;
        },
        //获取满赠参数
        getGiftParams(){
            return this.getGiftVOList;
        },
        //获取发票参数
        getFpParams(){
            var newObj = {};
            let obj = this.getFpObj;
            if(!obj){
                return;
            }
            if(obj.invoiceTitle == "单位"){
                newObj.invoiceType = obj.invoiceTypeCode;  //类型
                newObj.invoiceHead = obj.invoiceTitle ; // 抬头
                newObj.taxpayerNo = obj.taxpayerNo ;// 税号
                newObj.companyName = obj.companyName; // 公司名字
                newObj.invoiceContent  = obj.content ;  //发票内容
            }else if(obj.invoiceTitle == "个人"){
                newObj.invoiceType = obj.invoiceTypeCode;  //类型
                newObj.invoiceHead = obj.invoiceTitle ; // 抬头
                newObj.invoiceContent  = obj.content;   //发票内容
            }

            return newObj;
        },
        //是否使用钱包支付
        checkBuyByCard(){
            var flag = this.getUseGiftCard;
            return flag;
        },
        //获取免密金额
        getMoneyWithoutCode(data){
            if(data != null){
                this.moneyWithoutC = data;
            }
        },
        //获取应付金额
        getTotalMoney(money){
            this.totalMoney = money;
        },
        //将提交订单的地址  isNew置为 0
        setAddressIsNew(item){
            let params = {
                type:"UPDATE",
                userid: item.userid,
                addressid:item.addressid,
                enterprisecode:window.api.enterpriseCode
            }
            var sessionId = localStorage.getItem('sessionId');
            let config = {
                url: window.api.customer_host+'/address',
                method:'POST',
                data:params,
                headers: {'sessionId': sessionId, 'Content-Type':'application/json', 'Accept' : 'application/json'},
            }
            axios(config).then((res)=>{
                console.log(res);
            })
        },
        //弹出选择配送时间让用户确认，用户不点击确定就一直弹出 选择时间的弹出框
        makeSureTime(){
            let flag = this.$refs.nomalTimeshow.chooseFlag;
            let flagXiaDan = false;
            if(!flag){
                this.$refs.nomalTimeshow.showPop();
            }else{
                flagXiaDan = true;
            }
            return flagXiaDan;
        },
        //校验门店是否在配送范围内
        checkStoreRange(){
            // console.log(this.clickFlag,'点击开始');
            if(this.confirmOrderFood){
                this.confirmOrderFoods();
                return
            }
            
            // var that = this;
            // var myTimer = setTimeout(function(){
            //     that.clickFlag = true;
            // },5000)

            let payAddressFlag = this.getToPayAddress();  //获取用户收货地址

            if(!payAddressFlag){
                return;
            }

            if(!this.sessionId){
                this.$router.push('login');
            }
            // console.log(this.getOrderFlag,this.address,'地址信息');
            
            if(!this.address || !this.address.addressid || this.address.addressid==-1){
                // Toast({
                //     message: '请选择收货地址',
                //     duration: 1000,
                //     type:'fail'
                // });
                // var myAddress = this.getLocation;
                // console.log(myAddress,"myAddress/*/*/*//**/*/*/*/*")
                var address = {
                    address:'',
                    city:'',
                    defaultaddress:"1",
                    label:"0",
                    phone:"",
                    positionlat:'',
                    positionlng:'',
                    province:'',
                    receivername:"",
                    region:'',
                    result:"",
                    sex:"0",
                    houseNumber:''
                }
                this.setaddFlagMutation(true);
                this.setNowAddressMutation(address);
                let arr = this.userInfo.addressLists;
                //  console.log(arr,"66666666666-----")
                if(arr && arr.length != 0){
                    this.$router.push({ path: 'address',query:{id:1}});
                }else{
                    this.$router.push({ path: 'address',query:{id:1}});
                }
                return
            }
            // console.log(this.clickFlag,'防止多次点击')
            //防止多次点击下单
            if(!this.clickFlag){
                return ;
            }
            // 判断配送时间接口是否已返回数据 并且有可用的配送时间 没返回就禁止下单
            // if(!this.getOrderFlag){
            //     Toast({
            //         message: '暂无可配送时间',
            //         duration: 1000,
            //         type:'fail'
            //     });
            //     return;
            // }
            let flagXiaDan = this.makeSureTime();
            if(!flagXiaDan){
                return
            }
            this.clickFlag = false;  // 点击后置为禁用状态            

            var url = window.api.customer_host + "/address/getTMS";
            var params = {
                longitudeandlatitude:this.address.positionlng + ',' + this.address.positionlat
            }
            var config = {
                url:url,
                method:"GET",
                params
            }
            axios(config).then((res)=>{
                // console.log(res.data.returnCode,'校验配送地址');
                if(res.data.returnCode == 0){
                    Toast({
                        message: '该地址不在配送范围内',
                        duration: 1000,
                        type:'fail'
                    });
                    setTimeout(()=>{
                        this.clickFlag = true;  //接口返回  解除点击禁用
                    },300)

                }else if(res.data.returnCode == 1){
                    //如果地址存在  将该地址推送到首页和选择地址页
                    // console.log(res.data.data[0],'----------88888---------------------------------------------------');
                    this.setAddressIsNew(this.address);
                    localStorage.setItem('locateIn',JSON.stringify(this.address));
                    this.$store.dispatch('qxz/updateLocation', this.address);
                    var latticeName = res.data.data[0].latticename;
                    this.sendOrder(latticeName);
                }
            })
        },
        //堂食订单提交方法
        async confirmOrderFoods(){
            // if(!this.isOpenShops){
            //      Toast({
            //         message: '当前门店未开启，请稍后点餐!',
            //         duration: 1000,
            //         type:'fail'
            //     });
            //     return;
            // }
            //防止多次点击下单
            if(!this.clickFlag){
                return ;
            }
            var myreg=/^[1][0-9]{10}$/;
            // var myreg=/^[1][0-9]{10}$/;
            if(!myreg.test(this.getConfirmobile)){
                Toast({
                    message: '手机号码格式不正确',
                    duration: 1000,
                    type: 'fail'
                });
                return;
            }
            let params = {
                deliveryType:this.getConfirstyle && this.getConfirstyle == "到店堂食" ?"DDST":"DDDB",  //配送方式
                storeCode:localStorage.getItem('storeId'), //调试用的 '5555555'  localStorage.getItem('storeId')   3df87595-762d-414e-be0f-6b6d8361f5d2  73ece0ae-ba0e-4501-b993-d727b9ae25c2
                orderType:tangshi?'3':"",
                orderMobile:this.getConfirmobile,
            };
            let flages = this.$store.state.hzh.BillBtn;//是否点击了确认的标志 每次进入选择发票页面清空该值
            let electronicInvoice = {//发票的传参
                invoicesTitleId:this.$store.state.hzh.getBillInfor,
                invoiceContext:this.$store.state.hzh.BillContent
            }
            if(flages){//添加发票参数
                params.electronicInvoice =electronicInvoice;
            }
            if(this.PutAShopLacks){//添加缺货参数
                params.outStockModel = this.PutAShopLacksFood
            }
            // let flag = this.checkBuyByCard();//入参 walletPayed 0 代表常规支付   1代表钱包支付
            // if(flag){
            //     params.walletPayed = 1;
            // }else{
            //     params.walletPayed = 0;
            // }
            var couponParams = this.getCouponParams();  // 获取优惠券参数
            if(couponParams && couponParams.length != 0){
                params.qrCodeList = couponParams;
            }
            // console.log("打印优惠券",couponParams)
            var ladderIdList = this.getLadderParams(); // 获取阶梯返利满赠参数
            if(ladderIdList && ladderIdList.length != 0){
                params.ladderIdList = ladderIdList;
            }
            // var giftVOList = this.getGiftParams();
            // if(giftVOList && giftVOList.length != 0){
            //     params.giftVOList = giftVOList;
            // }
            let query = this.$route.query.name;
            params.token  = this.$store.state.hzh.shopInforToken;  // 传token用于后台识别
            // console.log(this.getToken,'this.getToken获取token提交');
            this.clickFlag = false;//接口返回  点击禁用
            console.log(params,'下单参数');
            let config = {
                url: window.api.trade_host+'/order/insertDto',
                method: 'POST',
                data: params,
                headers: {'sessionId': this.sessionId, 'Content-Type':'application/json', 'Accept' : 'application/json'},
            }
            try{
                let data = await axios(config);
                // console.log(params,'下单请求参数信息')
                // console.log(data,'返回参数')
                if(data.data.returnCode === 1 ){
                    // this.clickFlag = true;//接口返回  接口返回  解除点击禁用
                    // console.log(this.totalMoney,'订单生成');
                    this.$store.dispatch('hzh/PutFoodInfors', "到店食堂");
                    var arr = [];
                    // this.changeCheckedCartList(arr);
                    this.$store.dispatch("lyj/changeCheckedCartListly",arr)
                    this.$store.dispatch('lyj/queryCart');

                    var orderNo = data.data.data[0];
                    if(this.totalMoney != 0){
                        this.$router.push({name: "pay", params: {orderNo:orderNo,orderType:tangshi}});
                    }else{
                        this.$router.push({name: "paysuccessfully", params: {orderNo:orderNo,orderType:tangshi}});
                    }
                }else if(data.data.returnCode === 3 ){//存在待支付的订单，不能下单，并前往待付款订单
                        var token = data.data.data[0];
                        // console.log('token失败------',this.getToken,'this.getToken获取token失败------');
                        this.setToken(token);  //下单失败 后台重新返回 token 用于再次下单
                        MessageBox.confirm(data.data.msg,).then((action)=>{
                            // if(this.confirmOrderFood){
                            //     console.log("有没有调用calOrder接口7")
                            //     this.$router.push('cartForFood');
                            // }else{
                                this.$router.push({name: "order",query:{orderStatus:1}});
                            // }
                        }).catch(() => {
                            console.log("afdasfasfasfasfa******************************")
                            this.clickFlag = true;//接口返回  接口返回  解除点击禁用
                            // this.$message({
                            //     type: 'info',
                            //     message: '取消'
                            // });       
                        });
                }else{
                    var token = data.data.data[0];
                    this.clickFlag = true;//接口返回  接口返回  解除点击禁用
                    // console.log('token失败------',this.getToken,'this.getToken获取token失败------');
                    this.setToken(token);  //下单失败 后台重新返回 token 用于再次下单
                    MessageBox.confirm(data.data.msg).then((action)=>{
                        this.$router.push('cartForFood');
                    
                    })
                }
            }catch(err) {
                console.log(err,'错误信息')
                this.clickFlag = true;  //接口返回  解除点击禁用
                Toast({
                    message: '生成订单失败',
                    duration: 1000,
                    type: 'fail'
                });
            }
        },
        //判断门店模式是否开启
        isOpenShop(){
            let data = {
                storeId:window.localStorage.getItem("storeId"),
                enterpriseCode:window.api.enterpriseCode,
            }
            let sessionId =  window.localStorage.sessionId;
            let config = {
                url: window.api.base_host+'/baseStore/checkStoreOpen',
                method:"GET",
                params: data,
                headers: {'sessionId': sessionId},
            }
            axios(config).then((res) => {
                // console.log("判断门店模式是否开启1111111111113",res)
                try {
                    this.isOpenShops = res.data.data[0].storeOpen;
                } catch (error) {
                    
                }
            })
        },
        //生成订单
        async sendOrder(latticeName){
            var orderDeliveryTms  = [];
            var norObj = {};
            var bigObj = {};
            var changeTmObj = {};//效验推送时间的传参 常规
            var changeTmObjs = {};//效验推送时间的传参 大件
            var changTmArr = [];//效验推送时间的传参de 集合
            var norMalTime = this.getTimeNormal;
            var bigTime = this.getTimeBig;
            let storeCode = localStorage.getItem("storeCode");
            // console.log(this.maxTimeNormal,this.maxTimeBig,bigTime,'this.maxTimeNormalthis.maxTimeNormalthis.maxTimeNormalthis.maxTimeNormal')
            // let tempTime = new Date();
            // tempTime = tempTime.setDate(tempTime.getDate() - 1);
            // console.log(norMalTime,bigTime,'配送时间')
            if(norMalTime &&  this.maxTimeNormal &&  this.maxTimeNormal.length){
                norObj.expectedTmStart = norMalTime.startPeriodTm;
                norObj.expectedTmEnd = norMalTime.endPeriodTm;
                norObj.showStartTm = norMalTime.startBookTm;
                norObj.showEndTm = norMalTime.endBookTm;
                norObj.goodsDeliveryType = 0;
                norObj.maxMachineTm = this.maxTimeNormal[1];
                changeTmObj.deliveryType = 0;
                changeTmObj.machineTm = this.maxTimeNormal[1];
                changeTmObj.startBookTm = norMalTime.startBookTm;
                changeTmObj.storeCode = storeCode;
                // changeTmObj.startBookTm = tempTime;
            }
            if(bigTime && this.maxTimeBig && this.maxTimeBig.length){
                bigObj.expectedTmStart = bigTime.startPeriodTm;
                bigObj.expectedTmEnd = bigTime.endPeriodTm;
                bigObj.showStartTm = bigTime.startBookTm;
                bigObj.showEndTm = bigTime.endBookTm;
                bigObj.goodsDeliveryType = 1;
                bigObj.maxMachineTm = this.maxTimeBig[1];
                changeTmObjs.deliveryType = 1;
                changeTmObjs.machineTm = this.maxTimeBig[1];
                changeTmObjs.startBookTm = bigTime.startBookTm;
                changeTmObjs.storeCode = storeCode;
            }
            if(this.checkedCartListNormal.length != 0){
                orderDeliveryTms.push(norObj);
                changTmArr.push(changeTmObj);
            }
            if(this.checkedCartListBig.length != 0){
                orderDeliveryTms.push(bigObj);
                changTmArr.push(changeTmObjs)
            }
            console.log("2222222222222",this.normalTimeList,this.bigTimeList)
            if(this.normalTimeList){
                if(this.checkedCartListNormal.length > 0){
                    if( this.normalTimeList.length == 0 || this.normalTimeList[0].deliveryList.length == 0){
                        Toast({
                            message: '暂无可配送时间',
                            duration: 1000,
                            type:'fail'
                        });
                        this.clickFlag = true
                        return
                    }

                }
            }

            if(this.bigTimeList){
                // console.log('下单++++++++++++++++++++++++++++++++++==',this.bigTimeList)
                if(this.checkedCartListBig.length > 0){
                    if(this.bigTimeList.length == 0 || this.bigTimeList[0].deliveryList.length == 0){
                        Toast({
                            message: '暂无可配送时间',
                            duration: 1000,
                            type:'fail'
                        });
                        this.clickFlag = true
                        return
                    }
                }
            }
            // if(!bigTime || bigTime.valid == 0){
            //     Toast({
            //         message: '大件商品暂无可配送时间',
            //         duration: 1000,
            //         type:'fail'
            //     });
            //     return
            // }
            // if(!norMalTime || norMalTime.valid == 0){
            //     Toast({
            //         message: '常规商品暂无可配送时间',
            //         duration: 1000,
            //         type:'fail'
            //     });
            //     return
            // }
            //获取对象的length
            if(!Object.getOwnPropertyNames(orderDeliveryTms[0]).length){

                Toast({
                    message: '请选择配送时间',
                    duration: 1000,
                    type:'fail'
                });
                this.clickFlag = true
                return
            }
            // console.log(changTmArr,"查看参数是-------------------------------------------",changeOrderTm(false,changTmArr))
            var promise1 = Promise.resolve(changeOrderTm(false,changTmArr));
            await promise1.then((value)=> {
                console.log(value,"13902427893");
                if(!value.state){
                    this.tempTm = false;
                    // console.log("66666666666666666666666666666666666");
                    MessageBox.alert(value.msg).then((action)=>{
                        this.$router.push({name: "cart"});
                    })
                }
            });
            if(!this.tempTm){
                // console.log("777777777777777777777777777777777777777777");
                // this.$refs.nomalTimeshow.showPop();
                this.clickFlag = true
                return
            }
           
            
            //校验配送方式
            if(!this.getDeliveryType){
                Toast({
                    message: '未获取到配送方式',
                    duration: 1000,
                    type:'fail'
                });
                return
            }
            let electronicInvoice = {
					invoicesTitleId:this.$store.state.hzh.getBillInfor,
					invoiceContext:this.$store.state.hzh.BillContent
				}
            // let params = {};
            let params = {
                    addressId:this.address.addressid,
                    // cartId:this.checkedCartList[0].cartId,
                    deliveryType:this.getDeliveryType,  //配送方式
                    note:this.getMynode,
                    // shopCartIds:this.shopCartIds,
                    storeCode:localStorage.getItem('storeId'), //调试用的 '5555555'  localStorage.getItem('storeId')   3df87595-762d-414e-be0f-6b6d8361f5d2  73ece0ae-ba0e-4501-b993-d727b9ae25c2
                    orderDeliveryTms,
                    latticeName:latticeName,// wms网格 
                    
                };
            if(this.PutAShopLacks){//添加缺货参数
                params.outStockModel = this.PutAShopLacks
            }
            if(this.$store.state.hzh.getBillInfor.length != 0 && this.$store.state.hzh.BillBtn){//添加发票参数
                params.electronicInvoice =electronicInvoice;
            }
            // console.log("提交订单------------------>",params)
            let flag = this.checkBuyByCard();//入参 walletPayed 0 代表常规支付   1代表钱包支付
            if(flag){
                params.walletPayed = 1;
            }else{
                params.walletPayed = 0;
            }
            var couponParams = this.getCouponParams();  // 获取优惠券参数
            if(couponParams && couponParams.length != 0){
                params.qrCodeList = couponParams;
            }
            // console.log("打印优惠券",couponParams)
            var ladderIdList = this.getLadderParams(); // 获取阶梯返利满赠参数
            if(ladderIdList && ladderIdList.length != 0){
                params.ladderIdList = ladderIdList;
            }

            var giftVOList = this.getGiftParams();
            if(giftVOList && giftVOList.length != 0){
                params.giftVOList = giftVOList;
            }
            // if(Object.keys(this.getFpObj).length){
            //     var fpParams = this.getFpParams();  // 获取发票参数
            // }

            // if(fpParams){
            //     params.orderInvoice = fpParams;
            // }

            let query = this.$route.query.name;

            params.deliveryAddress = this.getAddressDetail;

            params.token  = this.getToken;  // 传token用于后台识别
            // console.log(this.getToken,'this.getToken获取token提交');
            console.log(params,'下单参数');
            let config = {
                url: window.api.trade_host+'/order/insertDto',
                method: 'POST',
                data: params,
                headers: {'sessionId': this.sessionId, 'Content-Type':'application/json', 'Accept' : 'application/json'},
            }
            if(this.address && orderDeliveryTms.length > 0){
                try{
                    let data = await axios(config);
                    // console.log(params,'下单请求参数信息')
                    setTimeout(() => {
                        this.clickFlag = true;  //接口返回  解除点击禁用
                    },300)
                    console.log(data,'返回参数')
                    if(data.data.returnCode == 1 ){
                        // console.log(this.totalMoney,'订单生成');
                        var arr = [];
                        this.changeCheckedCartList(arr);
                        this.$store.dispatch('cjy/queryCart');
                        var orderNo = data.data.data[0];
                        if(this.totalMoney != 0){
                            this.$router.push({name: "pay", params: {orderNo:orderNo,orderType:normal}});
                        }else{
                            this.$router.push({name: "paysuccessfully", params: {orderNo:orderNo,orderType:normal}});
                        }
                    }else if(data.data.returnCode == 3 ){//存在待支付的订单，不能下单，并前往待付款订单
                        // var token = data.data.data[0];
                        // console.log('token失败------',this.getToken,'this.getToken获取token失败------');
                        // this.setToken(token);  //下单失败 后台重新返回 token 用于再次下单
                        MessageBox.confirm(data.data.msg).then((action)=>{
                            
                            this.$router.push({name: "order",query:{orderStatus:1}});
                            
                        })
                    }else{
                        var token = data.data.data[0];
                        // console.log('token失败------',this.getToken,'this.getToken获取token失败------');
                        this.setToken(token);  //下单失败 后台重新返回 token 用于再次下单
                        // this.$refs.popoutCover.showCover()
                        // this.texts = data.data.msg;
                        var TooLong = true;
                        MessageBox.alert(data.data.msg,"提示","",TooLong).then((action)=>{
                            this.$router.push('cart');
                        })
                        
                    }
                }catch(err) {
                    console.log(err,'错误信息')
                    this.clickFlag = true;  //接口返回  解除点击禁用
                    Toast({
                        message: '生成订单失败',
                        duration: 1000,
                        type: 'fail'
                    });
                }
            }
        },
        //滚动事件
        createdScroll() {
            // 如果bscroll实例存在那么就先销毁实例
            this.Bscroll && this.Bscroll.destroy()
            //拿到dom元素
            // 初始化实例
            this.Bscroll = new Bscroll(".bs-wrapper", {
                // scrollY: true,
                // click: true,
                bounce: false,
                // swipeBounceTime: 2000,
                // deceleration: 0.0015,
                // freeScroll: true,
                // momentum: true,
                // probeType: 3,
                // mouseWheel: true,
                eventPassthrough: 'horizontal',
            });
        
            // this.content = document.querySelector("#content-container");
            this.Bscroll.on("scroll", () => {
                //实现第一部分功能
                // console.log("jin没有进来")
            })
        },
        //阻止浏览器默认行为触发的通用方法  
        stopDefault(e){  
            //防止浏览器默认行为(W3C)  
            if(e && e.preventDefault){  
                e.preventDefault();  
            }  
            //IE中组织浏览器行为  
            else{  
                window.event.returnValue=false; //实际上在IE8以下，会报错
                return false; 
            }  
        },
       
    },
    created () {
        this.getmoneySend();
        this.confirmOrderFood = this.$route.query.confirmOrderFood;

        // if(this.confirmOrderFood){
        //      this.isOpenShop();//判断门店模式是否开启
        // };
        // this.stopDefault();
    },
    mounted () {
        setTimeout(() => { 
            this.createdScroll();
        }, 200)
        // this.appendToPay();
        //如果不是从缓存获取数据就showLoading
        if(!this.getDateFromCatch){
            // showLoading();
        }
    },
    updated() {
        //页面更新完毕
        this.$nextTick(() => {
            setTimeout(()=>{
                this.Bscroll.refresh()
            },750)
        });
       
    },
    beforeRouteLeave(to, from, next) {
       
        //只能在父组件中触发    如果去购物车或者支付页面就把vuex中的信息删除
        if(to.name == "CartForFood" ||to.name == "cart" || to.name == "pay" || to.name == "paysuccessfully"){
            this.setOrderFlag(false); //将禁止下单按钮点击
            let arr = [];
            this.setFpObj({});  // 清空发票
            this.setTicketList(arr);  //清空优惠券
            this.setUseGiftCard(false); // 清空钱包选择
            this.setMynode("");  // 清空留言
            this.setDateNormal(null); // 清空配送日期
            this.setDateBig(null);// 清空配送日期
            this.setTimeNormal({});// 清空配送时间
            this.setTimeBig({});// 清空配送时间
            this.setTimeSaveObj({});
            this.setConfrimOrderRes({});
            this.setNormalM({}); //清除常规商品配送费
            this.setBigM({}); //清除大件商品配送费
            this.$store.dispatch('hzh/PutFoodShopToken', "");
            this.$store.dispatch('hzh/GetBillInfor', "");
            this.$store.dispatch('hzh/SaveBillBtn', "");
        
        }
        console.log(to.name,'去到哪个页面');
        console.log(from.name,'cong哪个页面lai');
        next();
    },
}
</script>

<style scoped>
	.content{
		flex: 1;
		/* overflow-y: auto; */
        position: relative;
        top:-1px;
        overflow: hidden;
        /* overflow: hidden; */
         /* -webkit-overflow-scrolling : touch; */
    }
    .contentnew {
		flex: 1;
		-webkit-flex: 1;
		/* overflow-y: scroll; */
		width: 100%;
		overflow-x: hidden;
	}
	
    .zxBottomBtn{
        height:3rem;
        width:100%;
        display:flex;
        justify-content:flex-end;
        flex-direction: row;
        align-items: center;
        background: #fff;
    }
    .zxSendOrderPrice{
        font-size: 0.7rem;
        margin-right: 0.75rem;
    }
    .zxSendOrder{
        height: 3rem;
        font-size: 1rem;
        text-align: center;
        line-height: 3rem;
        background: #ef5423;
        padding: 0 1rem;
        color: #fff;
    }
	.box{
		width: 100%;
	    height: 100%;
		display: flex;
		justify-content: space-between;
		flex-direction: column;
	}
    .confrimOrderTopBar {
        width: 100%;
        height: 3.15rem;
        background: #38b035;
        position:absolute;
        top:0;
        left: 0;
        z-index: -1;
    }
    .confrimOrderTimeAddressBox {
        background-color: #fff;
        width: 93%;
        border-radius: 0.2rem;
        margin: 0 auto;
        min-height: 5.1rem;
    }
    .confrimOrderAddressBox{
        margin-right: 0.75rem;
        margin-left: 0.75rem;
        border-bottom: 1px solid #e8e8e8;
        height: 100%;
    }
    .confrimOrderTimeBox{
        margin-right: 0.75rem;
        margin-left: 0.75rem;
    }
    .zx_message{
        height: 2.5rem;
        width: 100%;
        position: absolute;
        left: 0;
        bottom: 3rem;
        z-index: 5;
        background: #fff3ef;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        padding-left: 0.75rem;
        /* padding-right: 1.75rem; */
    }
    .sbbjclass {
		position: relative;
		width: 100%;
		display: flex;
		flex-flow: column wrap;
		-webkit-flex-flow: column wrap;
		height: 100%;
		-webkit-overflow-scrolling: auto;
    }
    .mint-msgbox-message{
        text-align:left;
        padding:10px;
        line-height:25px;
    }
</style>